/*
 * @Autor: 郑祥
 * @Date: 2021-01-27 13:53:31
 * @LastEditTime: 2021-03-25 11:37:38
 * @FilePath: \fby-web\src\components\FileUpload\index.js
 * @LastEditors: 郑祥
 * @Description: 文件上传
 */
import React, { useState, useEffect } from 'react'
import { Modal, Upload, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { baseURL } from '@/axios';
const { Dragger } = Upload;

const FileUpload = props => {
  const [fileList, setfileList] = useState([])
  const [previewVisible, setpreviewVisible] = useState(false)
  const [previewTitle, setpreviewTitle] = useState("")
  const [previewImage, setpreviewImage] = useState("")
  useEffect(() => {
    setfileList(props.fileList)
  }, [props.fileList])
  const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  /**
   * @author: 郑祥
   * @param {Object} file
   * @description: 点击下载文件时的回调 
   *    dataURLtoBlob downloadFile handleDownload 这3个方法将Base64转为blob本地下载
   */
  // const handleDownload = file => {
  //   let myBlob = dataURLtoBlob(file.thumbUrl)
  //   let myUrl = URL.createObjectURL(myBlob)
  //   downloadFile(myUrl, file.name)
  // }
  // const dataURLtoBlob = (dataurl) => {
  //   let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  //     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  //   while (n--) {
  //     u8arr[n] = bstr.charCodeAt(n);
  //   }
  //   return new Blob([u8arr], { type: mime });
  // }
  // const downloadFile = (url, name = '1111') => {
  //   let a = document.createElement("a")
  //   a.setAttribute("href", url)
  //   a.setAttribute("download", name)
  //   a.setAttribute("target", "_blank")
  //   let clickEvent = document.createEvent("MouseEvents");
  //   clickEvent.initEvent("click", true, true);
  //   a.dispatchEvent(clickEvent);
  // }
  /**
   * @author: 郑祥
   * @param {Object} file
   * @description: 点击文件链接或预览图标时的回调
   */
  const handlePreview = async file => {
    if (file.name.split('.')[file.name.split('.').length - 1] === 'jpg' || file.name.split('.')[file.name.split('.').length - 1] === 'png' || file.name.split('.')[file.name.split('.').length - 1] === 'jpeg') {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      setpreviewImage(file.url || file.preview)
      setpreviewVisible(true)
      setpreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
    } else {
      var link = document.createElement('a');
      link.style.display = 'none';
      //设置下载路径
      link.href = file.url;
      // link.download = 'aaa';
      //触发点击
      document.body.appendChild(link);
      link.click();
      //移除节点
      document.body.removeChild(link);
    }
  };
  /**
   * @author: 郑祥
   * @param {Object} file
   * @description: 删除图片
   */
  const handleRemove = file => {
    const newFileList = fileList.slice();
    newFileList.splice(fileList.indexOf(file), 1);
    setfileList(newFileList)
    props.onChange(newFileList)
  }
  /**
   * @author: 郑祥
   * @param {Object} file
   * @description: 上传图片/文件
   */
  const handleChange = (info) => {
    let fileLists = [...info.fileList];
    fileLists = fileLists.map(file => {
      if (file.response) {
        file.url = file.response.data.fullUrl
        file.id = file.response.data.id
      }
      return file;
    });
    setfileList([...fileLists])
    props.onChange([...fileLists])
    // const { file } = e
    // if (file.status === 'uploading') {
    //   setfileList([...fileList, file])
    //   return;
    // }
    // if (file.status === 'done') {
    //   if (file.xhr && file.xhr.status === 200) {
    //     file.id = file.response.data.id
    //     file.url = file.response.data.fullUrl
    //     setfileList([...fileList, file])
    //     props.onChange([...fileList, file])
    //   }
    // } else if (file.status === 'removed') {
    //   setfileList([...e.fileList])
    //   props.onChange([...e.fileList])
    // }
  };
  /**
   * @author: 郑祥
   * @param {Object} file
   * @description: 图片上传前的判断
   */
  const handleBeforeUpload = file => {
    let isJpgOrPng = false;
    if (file.type.includes('image')) {
      if (file.name.split('.')[file.name.split('.').length - 1] === 'jpg' || file.name.split('.')[file.name.split('.').length - 1] === 'png' || file.name.split('.')[file.name.split('.').length - 1] === 'jpeg') {
        isJpgOrPng = true
      } else {
        message.error('请上传jpg、png、jpeg图片');
      }
    } else {
      isJpgOrPng = true
    }
    return isJpgOrPng;
  };
  const UploadProps = {
    action: `${baseURL}fastdfs/upload`,
    fileList,
    multiple: true,
    onPreview: handlePreview,
    // onDownload: handleDownload,
    onRemove: handleRemove,
    onChange: handleChange,
    beforeUpload: props.beforeUpload ? props.beforeUpload : handleBeforeUpload,
    headers: {
      'Auth-Token': JSON.parse(sessionStorage.getItem('userInfo')).token
    },
    showUploadList: {
      showPreviewIcon: true,
      // showDownloadIcon: true,
      showRemoveIcon: true,
    }
  }
  return (
    <>
      <Dragger {...UploadProps} accept={props.accept} disabled={props.disabled ? true : false}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖动文件上传</p>
        <p className="ant-upload-hint">{props.ts}</p>
      </Dragger>
      <Modal
        visible={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={() => {
          setpreviewVisible(false)
          setpreviewImage("")
        }}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  )
}

export default FileUpload